<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class UserShopCarModel extends Model {

    protected $table ="user_shop_car";

    protected $pk = 'shop_car_id';



    /*
* 获取total
* */
    public function getTotal($where=[]){
        return Db::name('user_shop_car')->where($where)->count();
    }


    /*
     * 获取list
     * */
    public function getList($where=[],$page = null,$limit = null,$orderField = null,$orderType = "ASC"){

        $obj =  Db::name('user_shop_car')->where($where);


        if(!empty($page) && !empty($limit)){
            $obj = $obj->page($page, $limit);
        }

        if(!empty($orderField) && !empty($orderType)){
            $obj = $obj->order($orderField, $orderType);
        }

        return $obj->select();
    }



    /*
 * 获取订单状态详情
 * */
    public function getInfo($id){
        $cacheKey = $this->cacheKey.$id;
        $redisModel = new RedisModel();
        $info = $redisModel->get($cacheKey);
        if($info){
            $info = json_decode($info,true);
        }else{
            $info = Db::name('user_shop_car')->find($id);
            $redisModel->set($cacheKey,json_encode($info,256),$this->cacheTime);
        }
        if($info){
            $info["shop_info"] = (new ShopsModel())->getInfo($info["shop_id"]);
            $info["product_info"] = (new ProductsModel())->getInfo($info["product_id"]);
            $info["spec_info"] = (new ProductSalesSpecsModel())->getInfo($info["spec_id"]);
            return $info;
        }
        return [];
    }




    /*
     * 商品添加到购物车
     * */
    public function addOne($data){
        return Db::name('user_shop_car')->save($data);
    }



    /*
    * 获取购物车指定商品的数量
    * */
    public function getShopCarProductsNum($uid,$spec_id){
        if(empty($uid) || empty($spec_id)){
            return 0;
        }

        $where =[];
        $where['shop_car_status'] = 1;
        $where['uid'] = $uid;
        $where['spec_id'] = $spec_id;
        return Db::name('user_shop_car')->where($where)->value("num");
    }


    /*
     * 改变购物车指定商品的数量
     * */
    public function changeUserShopProductNum($uid,$spec_id,$num){
        if(empty($uid) ||  empty($spec_id)){
            return false;
        }

        $where =[];
        $where['uid'] = $uid;
        $where['shop_car_status'] = 1;
        $where['spec_id'] = $spec_id;
        return $this->upateAll($where,["num"=>$num]);
    }


    /*
    * 删除操作
    * */
    public function delAll($where){
        return Db::name('user_shop_car')->where($where)->delete();
    }


    /*
  * 删除操作
  * */
    public function upateAll($where,$data){
        return Db::name('user_shop_car')->where($where)->update($data);
    }
}